package com.tencent.qf.common.gateway.mks;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tencent.qf.common.gateway.mks.dto.MKSCommonRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * 营销中台 远程调用
 */
@Slf4j
@Component
public class MKSClient {
    @Resource
    private RestTemplate httpClientTemplate;
    @Resource
    private MKSProperties mksProperties;

    public String post(MKSCommonRequest request, String apiPath) {
        long timestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        String sign = MKSApiUtils.sign(request, mksProperties.getAppId(), mksProperties.getAppKey(), timestamp);
        if (StringUtils.hasText(sign)){
            request.setSignature(sign);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        HttpEntity<String> entity = new HttpEntity<>(JSONObject.toJSONString(request), headers);
        log.info("post请求营销中台{} 入参{}", apiPath, JSON.toJSONString(entity));
        ResponseEntity<String> responseEntity = httpClientTemplate.postForEntity(mksProperties.getUrl()
                + apiPath, entity, String.class);
        log.info("post请求营销中台{} 出参{}", apiPath, JSON.toJSONString(responseEntity));
        if(responseEntity.getStatusCode() == HttpStatus.OK){
            return responseEntity.getBody();
        }
        return null;
    }

    public String get(MKSCommonRequest request, StringBuilder apiPath) {
        long timestamp =  LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        String sign = MKSApiUtils.sign(request, mksProperties.getAppId(), mksProperties.getAppKey(), timestamp);
        apiPath.append("&app_id=").append(mksProperties.getAppId());
        apiPath.append("&timestamp=").append(timestamp);
        apiPath.append("&signature=").append(sign);
        log.info("get请求运营活动平台{}", apiPath);
        ResponseEntity<String> responseEntity = httpClientTemplate.getForEntity
                (mksProperties.getUrl() + apiPath,String.class);
        log.info("get请求运营活动平台{} 出参{}", apiPath, JSON.toJSONString(responseEntity));
        if(responseEntity.getStatusCode() == HttpStatus.OK){
            return responseEntity.getBody();
        }
        return null;
    }
}
